<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实时日志</title>
    <style>

        .alert-info {
            padding: 2px 10px;
        }

        .ibox-content {
            background-color: #fff;
            color: inherit;
            padding: 15px 20px 20px;
            border-color: #e7eaec;
            -webkit-border-image: none;
            -o-border-image: none;
            border-image: none;
            border-style: solid solid none;
            border-width: 1px 0
        }
    </style>
</head>
<body>
<h2 class="text-center text-primary">Welcome</h2>

<div class="ibox-content" id="message">

</div>
</body>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">



    $(function () {
        $.ajax({
            type: 'GET',
            url: '/logOnline/url',
            success: function (data) {
                init(data);
            },
            error: function () {
                alert("出现错误！");
            }
        })
    });

    function init(url) {
        var websocket = null;
        //判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            websocket = new WebSocket("ws://" + url + "/logOnline");
        } else {
            alert('Not support websocket')
        }

        //连接发生错误的回调方法
        websocket.onerror = function () {
            setMessageInnerHTML("error");
        };

        //连接成功建立的回调方法
        websocket.onopen = function (event) {
            setMessageInnerHTML("open");
        }

        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            setMessageInnerHTML(event.data, 1);
        }

        //连接关闭的回调方法
        websocket.onclose = function () {
            setMessageInnerHTML("close");
        }

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            websocket.close();
        }

        //将消息显示在网页上
        function setMessageInnerHTML(data, type) {
            var node = $('<div class="alert alert-info"></div>');
            if (type == 1) {
                var color = "#3c763d";
                data = JSON.parse(data);
                if (data.level == "ERROR") {
                    color = "#a94442";
                } else if (data.level == "WARN") {
                    color = "#8a6d3b";
                } else if (data.level == "DEBUG") {
                    color = "#31708f";
                }
                data = data.timestamp + "&emsp;<span style='color: " + color + "'>" + data.level + "</span>&emsp;" + data.threadName + "&emsp;" + data.className + "&emsp;" + data.body;
            }
            node.html(data);
            $('#message').append(node);
        }

        //关闭连接
        function closeWebSocket() {
            websocket.close();
        }
    }

</script>
</html>